# -*- coding: utf-8 -*-
'''
Created on Feb 4, 2013

@author: LONG HOANG GIANG
'''

import sqlite3 as db
import os

class SQLite3Helper():
    
    database = ''
    connection = None
    
    def __init__(self, database):
        parent = os.path.dirname(database)
        if not os.path.isdir(parent): os.makedirs(parent, 0777)
        self.database = database
    
    def open(self, delete=True):
        if (delete and os.path.isfile(self.database)):
            os.unlink(self.database)
        self.connection = db.connect(self.database)
        self.createTable()

    def commit(self):
        if self.connection is not None:
            self.connection.commit()
    
    def close(self):
        if self.connection is not None:
            self.connection.close()
            del self.connection
        
    def ensureUnicodeInput(self, params):
        result = [] if type(params).__name__ == 'list' else ()
        for param in params:
            if type(param).__name__ != 'unicode':
                param = unicode(param)
            result.append(param)
        return result
    
    def validateUnicode(self, data):
        if not isinstance(data, unicode): 
            data = unicode(data)
        return data
    
    def execute(self, sql, *args):
        param = None
        if type(args).__name__ == 'tuple':
            if len(args) > 0:
                param = args[0]
                typename = type(param).__name__
                if typename != 'list' and typename != 'tuple':
                    param = [param]
        c = self.connection.cursor()
        ret = c.execute(sql) if param is None else c.execute(sql, param)
        c.close()
        return ret
        
    def createTable(self):
        '''you must implement this method'''
